<?php
namespace Common\Util;



class ArrayToCsvUtils{

    public $_useGbk = true;
    private $fp = null;

    public function __construct(){
        //打开PHP文件句柄,php://output 表示直接输出到php缓存
        $this->fp = fopen('php://output', 'a');
    }

    //设置头部
    public function cvsHeader($filename)
    {
        //error_reporting(0);
        if($this->_useGbk) {
            header("Content-type:text/csv;charset=gbk");//application/vnd.ms-excel
        } else {
            header("Content-type:text/csv;charset=utf-8");
        }
        header("Content-Disposition:attachment;filename=" . $filename);
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0,max-age=0');
        header('Expires:0');
        header('Pragma:public');

/*        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="会员信息.csv"');
        header('Cache-Control: max-age=0');*/


    }

    //采用putcsv封装格式
    public function outputData($data){

        foreach ($data as $key => $value) {

            //CSV的Excel支持GBK编码，一定要转换，否则乱码
            $data[$key] = mb_convert_encoding($value, 'GBK', 'UTF-8')."\t";
            //$data[$key]=iconv('utf-8', 'gb2312', $value)."\t";
        }
        fputcsv($this->fp,$data);

    }

    //刷新缓存，将PHP的输出缓存输出到浏览器上
    public function csvFlush(){
        ob_flush();
        flush();
    }

    //关闭输出流
    public function closeFile(){
        fclose($this->fp);
    }
}

